/*
 * @Author: hong bin
 * @Date: 2021-10-03 14:06:13
 * @LastEditTime: 2021-10-04 18:09:43
 * @Description: 加工区 负责生成组合图片
 * @FilePath: /PictureCombination/client/src/components/HomePage/Material.tsx
 */
import {
  FC,
  Fragment,
  MouseEventHandler,
  ReactElement,
  useCallback,
  useRef,
  useState,
} from "react";
import styled from "styled-components";
import ToolBar from "./ToolBar";
import html2canvas from "html2canvas";

const onMouseMove: MouseEventHandler<HTMLImageElement> = (e: any) => {
  e.preventDefault();
  const pageY = e.pageY || e.touches[0].clientY;
  const pageX = e.pageX || e.touches[0].clientX;
  const x = Number(e.currentTarget.getAttribute("startX"));
  const y = Number(e.currentTarget.getAttribute("startY"));
  const prevX = parseFloat(e.currentTarget.getAttribute("prevX") || "0");
  const prevY = parseFloat(e.currentTarget.getAttribute("prevY") || "0");
  e.currentTarget.style["top"] = `${prevY + pageY - y}px`;
  e.currentTarget.style["left"] = `${prevX + pageX - x}px`;
};

const onMouseUp: MouseEventHandler<HTMLImageElement> = e => {
  //@ts-ignore
  e.currentTarget.removeEventListener("mousemove", onMouseMove);
  //@ts-ignore
  e.currentTarget.removeEventListener("touchmove", onMouseMove);
};

// | MouseEventHandler<HTMLImageElement>
// | TouchEventHandler<HTMLImageElement> = e => {
const onMouseDown: any = (e: any) => {
  const startX = e.pageX || e.touches[0].clientX;
  const startY = e.pageY || e.touches[0].clientY;
  e.currentTarget.setAttribute("startX", startX.toString());
  e.currentTarget.setAttribute("startY", startY.toString());
  e.currentTarget.setAttribute("prevX", e.currentTarget.style.left);
  e.currentTarget.setAttribute("prevY", e.currentTarget.style.top);

  //@ts-ignore
  e.currentTarget.addEventListener("mousemove", onMouseMove);
  //@ts-ignore
  e.currentTarget.addEventListener("touchmove", onMouseMove);
};

interface IProps {
  cover: string | null; //覆盖在上面的图片
}

const Machining: FC<IProps> = ({ cover }): ReactElement => {
  const [image, setImage] = useState<string | null>(null); //上传的图片
  const picture = useRef<HTMLDivElement>(null);
  const coverRef = useRef<HTMLImageElement>(null);

  const uploadImage = useCallback(() => {
    const input = document.createElement("input");
    input.type = "file";
    input.onchange = e => {
      let files = null;
      //@ts-ignore
      files = e.target.files;
      if (!files) return;
      const reader = new FileReader();
      reader.onload = () => {
        console.log(reader.result);
        setImage(reader.result as string);
      };
      reader.readAsDataURL(files[0]);
    };
    input.click();
  }, []);

  const screenshots = useCallback(() => {
    picture.current &&
      html2canvas(picture.current, { scale: 4 }).then(function (canvas) {
        const link = document.createElement("a");
        link.href = canvas.toDataURL();
        link.download = "picture";
        link.click();
      });
  }, []);

  const onChangeSize = useCallback((value: number) => {
    coverRef.current &&
      (coverRef.current.style["transform"] = `scale(${value / 50})`);
  }, []);
  const onChangeOpacity = useCallback((value: number) => {
    coverRef.current && (coverRef.current.style["opacity"] = `${value / 100}`);
  }, []);

  return (
    <div>
      <ImageBox ref={picture}>
        {image ? (
          <Fragment>
            {cover ? (
              <img
                data-cover
                touch-action='none'
                src={cover}
                ref={coverRef}
                alt='显示出错'
                onMouseDown={onMouseDown}
                // @ts-ignore
                onTouchStart={onMouseDown}
                onMouseUp={onMouseUp}
                onMouseLeave={onMouseUp}
                // @ts-ignore
                onTouchCancel={onMouseUp}
                // @ts-ignore
                onTouchEnd={onMouseUp}
              />
            ) : null}
            <img draggable={false} src={image} alt='' />
          </Fragment>
        ) : null}
      </ImageBox>
      <span style={{ opacity: cover ? 1 : 0 }}>可拖动调整位置</span>
      <ToolBar
        uploadImage={uploadImage}
        download={screenshots}
        onChangeSize={onChangeSize}
        onChangeOpacity={onChangeOpacity}
      />
    </div>
  );
};

export default Machining;

const ImageBox = styled.div`
  width: 20rem;
  height: 20rem;
  box-shadow: 2px 2px 60px 0 #ccc;
  border-radius: 5px;
  position: relative;
  overflow: hidden;

  span {
    transition: opacity 0.3s linear;
  }

  & > img {
    width: 100%;
    height: 100%;
  }
  & > img[data-cover] {
    width: 50%;
    height: 50%;
    position: absolute;
    cursor: move;
    transform-origin: left top;
  }
`;
